<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/5/7
 * Time: 14:25
 */

namespace zhtfrontend\controllers;

use common\models\datas\Site;
use zhtfrontend\components\bases\BaseController;
use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\Classroom;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\Teacher;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\web\BadRequestHttpException;
use yii\helpers\Json;
use common\components\helpers\Tree;
use yii\widgets\ActiveForm;

class MechanicController extends BaseController
{

    public function actionIndex(){
        $site=Site::findOne(['id'=>Fun::getSiteId()]);
        if($site==null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if (\Yii::$app->request->isAjax) {
            if(\Yii::$app->request->post('param') != null){
                $param = Json::decode(\Yii::$app->request->post('param'));
            }
            \Yii::$app->response->format = Response::FORMAT_JSON;
            $ajax_object = new AjaxObject();
            $is_delete = isset($param['searchData']['is_delete'])?$param['searchData']['is_delete']:0;
            $mechanic = Mechanic::find()->where(['site_id'=>Fun::getSiteId(),'is_delete'=>$is_delete]);
            if(!empty($param['searchData'])){
                $search_data = array_filter($param['searchData']);
                if(!empty($search_data['name'])){
                    $mechanic->andWhere(['like', 'name', $search_data['name']]);
                }
                if(!empty($search_data['regist_name'])){
                    $mechanic->andWhere(['like', 'regist_name', $search_data['regist_name']]);
                }
                if(!empty($search_data['searchWay'])){
                    if($search_data['searchWay']==3){
                        $search_data['searchWay']=0;
                    }
                    $mechanic->andWhere(['status'=>$search_data['searchWay']]);
                }
            }
//            if(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'business_director') {
//                $mechanic->andWhere(['admin_id' => \Yii::$app->user->id]);
//            }
            if(isset(\Yii::$app->user->identity)&&\Yii::$app->user->identity->role == 'class_director') {
                $admin_id = \Yii::$app->user->id;
                $mechanic->andWhere(['admin_id' => $admin_id]);
            }
            $mechanic = $mechanic->indexBy('id')->orderBy(['id'=>SORT_ASC]);
            $mechanic = $mechanic->all();
            $tree = (new Tree(Fun::asArray($mechanic,['zhtfrontend_operate','teacher_count'])))->get_jquery_tree_array();
            $ajax_object->data = $tree;
            return $ajax_object;
        }
        return $this->render('index',['mode'=>$site->mode]);
    }

    public function actionCreate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $model = new Mechanic();
        $site=Site::findOne(['id'=>Fun::getSiteId()]);
        if($site==null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario='create';

        $auth = \Yii::$app->authManager;
        //$adminModel = Admin::find()->where(['role'=>'class_director']);//谁教的获取权限这样子获取？？？
        $class_dire_userids = $auth->getUserIdsByRole('class_director');
        $adminModel = Admin::find()->where(['in','id',$class_dire_userids]);
        if(\Yii::$app->user->identity->role == 'class_director'){
              $adminModel->andWhere(['id'=>\Yii::$app->user->id]);
              $model->admin_id = \Yii::$app->user->id;
        }
        $admin = $adminModel->all();

        $admin = ArrayHelper::map($admin,'id','name');

        $user_ids = $auth->getUserIdsByRole('mec_principal');
        $admin_formec = Admin::find()->where(['in','id',$user_ids])->andWhere(['or', ['mechanic_id' => null], ['mechanic_id' => 0]])->all();
        $admin_formec = ArrayHelper::map($admin_formec,'id','name');

        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->site_id = Fun::getSiteId();
            $model->user_id = \Yii::$app->user->id;
            $model->number =time();
            $model->coordinates = '36.156880,120.420720';
            $model->address = '青岛市李沧区书院路37号奥克斯广场三楼';
            $model->region = '李沧区';
            if ($model->save(false)) {
                $admin_id = $model->mec_principal;
                $admin = Admin::findOne($admin_id);
                $admin->mechanic_id = $model->id;
                $admin->save(false);
                return $this->redirectMessage('添加成功', Fun::url(['mechanic/index']));
            }
        }
        return $this->render('create', ['mode'=>$site->mode,'model'=>$model,'admin'=>$admin,'admin_formec'=>$admin_formec]);
    }


    public function actionUpdate()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '错误请求'));
        }
        $model = Mechanic::findOne(\Yii::$app->request->get('id'));
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $site=Site::findOne(['id'=>Fun::getSiteId()]);
        if($site==null){
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $auth = \Yii::$app->authManager;
        $class_dire_userids = $auth->getUserIdsByRole('class_director');
        $adminModel = Admin::find()->where(['in','id',$class_dire_userids]);

        if(\Yii::$app->user->identity->role == 'class_director'){
            $adminModel->andWhere(['id'=>\Yii::$app->user->id]);
            $model->admin_id = \Yii::$app->user->id;
        }
        $admin = $adminModel->all();
        $admin = ArrayHelper::map($admin,'id','name');
        $user_ids = $auth->getUserIdsByRole('mec_principal');
        $admin_formec = Admin::find()->where(['in','id',$user_ids])->andWhere(['or', ['mechanic_id' => null], ['mechanic_id' => [0,$model->id]]])->all();
        $admin_formec = ArrayHelper::map($admin_formec,'id','name');
        $admin_mec = Admin::find()->where(['in','id',$user_ids])->andWhere(['mechanic_id' => $model->id])->one();
        if(!empty($admin_mec)){
            $model->mec_principal = $admin_mec->id;
        }
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->user_id = \Yii::$app->user->id;
            $model->coordinates = '36.31,120.39';
            $model->address = '青岛市李沧区书院路37号奥克斯广场三楼';
            $model->region = '李沧区';
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '修改成功'), Fun::url(['mechanic/index']));
            }
        }else{
//            print_r($model->getErrors());die;
        }
        return $this->render('create', ['mode'=>$site->mode,'model'=>$model,'admin'=>$admin,'admin_formec'=>$admin_formec]);
    }

    public function actionDelete()
    {
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $mechanic_id = \Yii::$app->request->get('id');
        //$mids = Fun::getMechanicIdsforfrontend($mechanic_id);
        //print_r($mids);exit;
        $can_delete = true;
        $result = true;
        $teacher = Teacher::findOne(['mechanic_id'=>$mechanic_id]);
        $course = Course::findOne(['mechince_id'=>$mechanic_id]);
        if(!empty($teacher) || !empty($course)){
            $can_delete = false;
        }
        if($can_delete){
            $model = Mechanic::findOne($mechanic_id);
            if(!empty($model)){
                $model->is_delete = 1;
                if($model->save(false)){
                    $result = true;
                }else{
                    $result = false;
                }
            }
            if($result){
                return $this->redirectMessage(\Yii::t('zhtfrontend', '机构删除成功'), Fun::url(['mechanic/index']));
            }else{
                return $this->redirectMessage(\Yii::t('zhtfrontend', '机构删除失败，请重试'), Fun::url(['mechanic/index']));
            }
        }else{
            return $this->redirectMessage(\Yii::t('zhtfrontend', '机构或分机构存在教师、课程或教室的信息，不可删除'), Fun::url(['mechanic/index']));
        }
    }
    public function actionRecovery(){
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Mechanic::findOne(\Yii::$app->request->get('id'));
        $model->is_delete = 0;
        if($model->save(false)){
//            if($model->parent_id >0){
//                $parentModel = Mechanic::findOne($model->parent_id);
//                $parentModel->is_delete = 0;
//                $parentModel->save(false);
//            }
            return $this->redirectMessage(\Yii::t('zhtfrontend', '恢复成功'), Fun::url(['mechanic/index']));
        }else{
            return $this->redirectMessage(\Yii::t('zhtfrontend', '恢复失败，请重试'), Fun::url(['mechanic/index']));
        }
    }

}
